﻿using Login.DTO.User;
using Login.Service;
using Login.Web.Infrastructure;
using Login.Web.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using Utility.Exception;
using Utility.Ext;

namespace Login.Web.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        // GET: User
        public ActionResult Index()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(UserViewModel model)
        {
            try
            {
                if (model.Password == "" || model.UserName == "")
                {
                    return View(model);
                }
                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                UserDTO ret = ServiceManagerFactory.CreateUserManagementService(Guid.Empty).VerifyUser(model.UserName, model.Password.EncryptSha1());
                serializeModel.User = new UserModel
                {
                    Id = ret.Id.ToString(),
                    Name = ret.Name,
                    UserName = ret.UserName,
                    Email = ret.Email,
                    Expression = ret.Id.ToString() + ret.Name + ret.UserName + ret.Email

                };
                serializeModel.UserName = model.UserName;

                string userData = serializer.Serialize(serializeModel);
                var ticket = new FormsAuthenticationTicket(2, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, userData);
                string encryptTickey = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTickey);
                Response.Cookies.Remove(cookie.Name);
                Response.Cookies.Add(cookie);
                return Redirect("/Home/Index");
            }
            catch (PasswordNotMatchException ex)
            {
                Log.Error(ex, "无效的用户名和密码");
                ViewBag.ErrorMsg = "无效的用户名和密码";
            }
            return View(model);
            
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
    }
}